package logview;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.NoSuchElementException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ViewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static transient final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ViewServlet.class);
	private String filename = null;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		final String uri = req.getRequestURI();
		final String key = req.getRequestURI().substring(uri.lastIndexOf('/')+1, uri.lastIndexOf('.'));
		
		final Properties logs = new Properties();
		req.setAttribute("id", key);
		try {
			logs.load(new FileInputStream(filename));
		} catch (Exception e) {
			throw new ServletException("Error loading properties: "+e);
		}
		
		log.debug("id: "+key);
		if (logs.containsKey(key)) {
			final PrintWriter w = resp.getWriter();
			resp.setContentType("text/plain");
			if (isMicrosoft(req.getHeader("User-Agent"))) {
				w.write("Don't use Microsoft browsers, they're buggy, a security risk, and not standards compliant\n");
				w.write("we need to write this for MS browsers for their' bugs\n");
			}
			sendLog(w, new FileReader((String) logs.get(key))); 
		} else {
			throw new NoSuchElementException("Logfile for id "+key+" not found in "+logs);
		}
	}
	
	private boolean isMicrosoft(String header) {
		return header!=null && header.indexOf("MSIE")>=0;
	}

	private void sendLog(PrintWriter w, Reader reader) throws IOException {
		final LineNumberReader br = new LineNumberReader(reader);
		String l = null;
		while ((l = br.readLine())!=null) {
			w.write(br.getLineNumber()+": ");
			w.write(l);
			w.write("\n");
			w.flush();
		}
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO allow changing this filepath from init param
		filename = config.getServletContext().getRealPath("WEB-INF/logfiles.properties");
		log.debug(ViewServlet.class.getName()+" initialized");
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		log.debug(ViewServlet.class.getName()+" destroyed");
		super.destroy();
	}
}
